<template>
  <div class="ai-report-container">
    <el-scrollbar style="height: calc(100vh - 60px)">
      <div class="report-content">
        <div class="report-header">
        <div class="header-title">
          <h2>📊 AI智能报表分析</h2>
          <p class="subtitle">基于大模型的订单、发货、库存预测分析系统</p>
        </div>
        <div class="header-actions">
          <el-radio-group v-model="selectedDays" size="default" @change="loadData">
            <el-radio-button :value="7">近7天</el-radio-button>
            <el-radio-button :value="15">近15天</el-radio-button>
            <el-radio-button :value="30">近30天</el-radio-button>
            <el-radio-button :value="60">近60天</el-radio-button>
          </el-radio-group>
          <el-button type="primary" :icon="RefreshRight" @click="refreshData" :loading="loading">
            {{ loading ? '加载中...' : '刷新数据' }}
          </el-button>
        </div>
      </div>

      <div class="update-time" v-if="updateTime">
        <el-icon><Clock /></el-icon>
        数据更新时间：{{ updateTime }}
      </div>

      <!-- AI综合建议 -->
      <div class="suggestions-card" v-if="suggestions.length > 0">
        <div class="card-title">
          💡
          <span>AI智能建议</span>
        </div>
        <div class="suggestions-list">
          <div v-for="(suggestion, index) in suggestions" :key="index" class="suggestion-item">
            <span>{{ suggestion }}</span>
          </div>
        </div>
      </div>

      <!-- 图表区域 -->
      <div class="charts-container">
        <!-- 订单趋势图 -->
        <div class="chart-card">
          <div class="card-header">
            <div class="card-title">
              <el-icon><TrendCharts /></el-icon>
              <span>订单趋势分析</span>
            </div>
            <el-tag :type="getTagType(orderPrediction.trend)" size="large">
              {{ orderPrediction.trend }}
            </el-tag>
          </div>
          <div class="chart-wrapper">
            <div ref="orderChart" class="chart"></div>
          </div>
          <div class="prediction-text">
            <el-icon><ChatDotRound /></el-icon>
            <span>{{ orderPrediction.analysis }}</span>
          </div>
        </div>

        <!-- 发货趋势图 -->
        <div class="chart-card">
          <div class="card-header">
            <div class="card-title">
              <el-icon><Van /></el-icon>
              <span>发货趋势分析</span>
            </div>
            <el-tag :type="getTagType(shipmentPrediction.trend)" size="large">
              {{ shipmentPrediction.trend }}
            </el-tag>
          </div>
          <div class="chart-wrapper">
            <div ref="shipmentChart" class="chart"></div>
          </div>
          <div class="prediction-text">
            <el-icon><ChatDotRound /></el-icon>
            <span>{{ shipmentPrediction.analysis }}</span>
          </div>
        </div>

        <!-- 库存趋势图 -->
        <div class="chart-card">
          <div class="card-header">
            <div class="card-title">
              <el-icon><Box /></el-icon>
              <span>库存趋势分析</span>
            </div>
            <el-tag :type="getTagType(inventoryPrediction.trend)" size="large">
              {{ inventoryPrediction.trend }}
            </el-tag>
          </div>
          <div class="chart-wrapper">
            <div ref="inventoryChart" class="chart"></div>
          </div>
          <div class="prediction-text">
            <el-icon><ChatDotRound /></el-icon>
            <span>{{ inventoryPrediction.analysis }}</span>
          </div>
        </div>
      </div>

      <!-- 数据统计卡片 -->
      <div class="stats-cards">
        <div class="stat-card">
          <div class="stat-icon order-icon">
            <el-icon><DocumentCopy /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">平均订单量</div>
            <div class="stat-value">{{ orderPrediction.average }} <span class="unit">单/天</span></div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon shipment-icon">
            <el-icon><Van /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">平均发货量</div>
            <div class="stat-value">{{ shipmentPrediction.average }} <span class="unit">单/天</span></div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon inventory-icon">
            <el-icon><Box /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">平均库存量</div>
            <div class="stat-value">{{ inventoryPrediction.average }} <span class="unit">件</span></div>
          </div>
        </div>
      </div>
      </div>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, getCurrentInstance, nextTick } from 'vue';
import * as echarts from 'echarts';
import * as signalR from '@microsoft/signalr';
import { 
  RefreshRight, Clock, TrendCharts, Van, Box, 
  ChatDotRound, DocumentCopy
} from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance();

// SignalR连接
let connection = null;

// 响应式数据
const selectedDays = ref(30);
const loading = ref(false);
const updateTime = ref('');
const suggestions = ref([]);

// 预测数据
const orderPrediction = ref({
  trend: '平稳',
  average: 0,
  prediction: [],
  analysis: '暂无数据'
});

const shipmentPrediction = ref({
  trend: '平稳',
  average: 0,
  prediction: [],
  analysis: '暂无数据'
});

const inventoryPrediction = ref({
  trend: '平稳',
  average: 0,
  prediction: [],
  analysis: '暂无数据'
});

// 图表实例
const orderChart = ref(null);
const shipmentChart = ref(null);
const inventoryChart = ref(null);

let orderChartInstance = null;
let shipmentChartInstance = null;
let inventoryChartInstance = null;

// 自动刷新定时器（已移除，改用服务端定时推送）
// let autoRefreshTimer = null;

/**
 * 获取标签类型
 */
const getTagType = (trend) => {
  if (trend === '上升') return 'success';
  if (trend === '下降') return 'danger';
  return 'info';
};

/**
 * 加载数据
 */
const loadData = async () => {
  try {
    loading.value = true;
    console.log('📊 开始加载AI报表数据，天数:', selectedDays.value);

    const res = await proxy.http.get(`/api/AIReport/GetAnalysisData?days=${selectedDays.value}`);
    
    console.log('API响应:', res);

    if (res && res.status && res.data) {
      const { data } = res;
      
      console.log('📊 收到后端数据:', data);
      console.log('📊 订单数据:', data.orders);
      console.log('📊 发货数据:', data.shipments);
      console.log('📊 库存数据:', data.inventory);
      
      // 更新预测数据
      if (data.prediction) {
        orderPrediction.value = data.prediction.order || orderPrediction.value;
        shipmentPrediction.value = data.prediction.shipment || shipmentPrediction.value;
        inventoryPrediction.value = data.prediction.inventory || inventoryPrediction.value;
        suggestions.value = data.prediction.suggestions || [];
        updateTime.value = data.prediction.updateTime || '';
      }

      // 等待DOM更新后绘制图表
      await nextTick();
      
      try {
        // 绘制图表（使用后端返回的真实数据和Y轴范围）
        const yAxisRanges = data.yAxisRanges || {};
        
        if (data.orders && data.orders.length > 0) {
          renderOrderChart(data.orders, yAxisRanges.orderMax);
        }
        
        if (data.shipments && data.shipments.length > 0) {
          renderShipmentChart(data.shipments, yAxisRanges.shipmentMax);
        }
        
        if (data.inventory && data.inventory.length > 0) {
          renderInventoryChart(data.inventory, yAxisRanges.inventoryMax);
        }
      } catch (error) {
        console.error('❌ 绘制图表失败:', error);
      }
    } else {
      console.error('数据格式错误:', res);
    }
  } catch (error) {
    console.error('❌ 加载数据失败:', error);
  } finally {
    loading.value = false;
  }
};

/**
 * 刷新数据
 */
const refreshData = () => {
  loadData();
};

/**
 * 绘制订单趋势图（真实数据 + AI预测，从最晚到最早）
 */
const renderOrderChart = (orders, yMax) => {
  if (!orderChart.value) {
    console.error('❌ 订单图表容器不存在');
    return;
  }

  // 检查数据是否有效
  if (!orders || !Array.isArray(orders) || orders.length === 0) {
    console.warn('⚠️ 订单数据为空或格式不正确');
    return;
  }

  console.log('📊 开始绘制订单图表，数据量:', orders.length);
  console.log('📊 AI预测数据:', orderPrediction.value);

  try {
    // 如果图表实例已存在，先销毁
    if (orderChartInstance) {
      orderChartInstance.dispose();
    }

    orderChartInstance = echarts.init(orderChart.value);
    
    // 设置图表自适应
    window.addEventListener('resize', () => {
      orderChartInstance?.resize();
    });

    // 真实历史数据（每条订单的实际数量，已经是倒序：从最晚到最早）
    const historicalData = orders.map(o => ({
      value: o.count || 0,
      orderNo: o.orderNo || '',
      date: o.date || ''
    }));
    
    // X轴时间标签（从最晚到最早，格式化显示）
    const timeLabels = orders.map(o => {
      try {
        const date = new Date(o.date);
        return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${String(date.getMinutes()).padStart(2, '0')}`;
      } catch (error) {
        console.error('❌ 时间格式化失败:', o.date, error);
        return '未知时间';
      }
    });

    // AI预测数据（未来7天）
    const predictionValues = orderPrediction.value.prediction || [];
    const lastDate = orders.length > 0 ? new Date(orders[0].date) : new Date();
    const predictionLabels = [];
    for (let i = 1; i <= 7; i++) {
      const futureDate = new Date(lastDate);
      futureDate.setHours(futureDate.getHours() + i);
      predictionLabels.push(`${futureDate.getMonth() + 1}-${futureDate.getDate()} ${futureDate.getHours()}:${String(futureDate.getMinutes()).padStart(2, '0')}`);
    }

    // 合并X轴标签（历史 + 预测）
    const allLabels = [...timeLabels, ...predictionLabels];

    // 历史数据系列（包含最后一个点连接到预测）
    const historicalSeries = [...historicalData.map(d => d.value), historicalData.length > 0 ? historicalData[0].value : 0];

    // 预测数据系列（从最后一个历史数据点开始，前面用'-'占位使得连续）
    const lastHistoricalValue = historicalData.length > 0 ? historicalData[0].value : 0;
    const predictionSeries = [...historicalData.map(() => '-'), lastHistoricalValue, ...predictionValues];

    // 计算Y轴最大值（包含预测数据）
    const allValues = [...historicalData.map(d => d.value), ...predictionValues].filter(v => v > 0);
    const maxValue = yMax || (allValues.length > 0 ? Math.max(...allValues) * 1.2 : 100);

  const option = {
    title: {
      text: '订单趋势分析（真实数据 + AI预测）',
      textStyle: { fontSize: 14, fontWeight: 'normal' }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'cross' },
      formatter: function(params) {
        let result = `时间: ${params[0].axisValue}<br/>`;
        params.forEach(param => {
          if (param.value !== null && param.value !== undefined) {
            result += `${param.seriesName}: ${Math.round(param.value)} 单<br/>`;
          }
        });
        return result;
      }
    },
    legend: {
      data: ['历史数据', 'AI预测'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: allLabels,
      name: '时间（左：历史数据，右：AI预测）',
      nameLocation: 'middle',
      nameGap: 30,
      axisLabel: {
        rotate: 45,
        interval: 'auto',
        formatter: function(value) {
          return value;
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '订单数量（单）',
      nameLocation: 'middle',
      nameGap: 50,
      min: 0,
      max: maxValue, // 使用动态计算的最大值
      axisLine: {
        show: true,
        lineStyle: {
          color: '#ddd'
        }
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#f0f0f0',
          type: 'dashed'
        }
      },
      axisLabel: {
        formatter: '{value}'
      }
    },
    series: [
      {
        name: '历史数据',
        type: 'line',
        data: historicalSeries,
        smooth: false,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: '#5470c6'
        },
        lineStyle: {
          width: 3
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(84, 112, 198, 0.3)' },
            { offset: 1, color: 'rgba(84, 112, 198, 0.05)' }
          ])
        }
      },
      {
        name: 'AI预测',
        type: 'line',
        data: predictionSeries,
        smooth: true,
        symbol: 'diamond',
        symbolSize: 10,
        itemStyle: {
          color: '#ee6666'
        },
        lineStyle: {
          width: 3,
          type: 'dashed'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(238, 102, 102, 0.2)' },
            { offset: 1, color: 'rgba(238, 102, 102, 0.05)' }
          ])
        }
      }
    ]
  };

  orderChartInstance.setOption(option);
  console.log('✅ 订单图表绘制成功');
  } catch (error) {
    console.error('❌ 绘制订单图表失败:', error);
    throw error;
  }
};

/**
 * 绘制发货趋势图（真实数据 + AI预测，从最晚到最早）
 */
const renderShipmentChart = (shipments, yMax) => {
  if (!shipmentChart.value) return;

  if (shipmentChartInstance) {
    shipmentChartInstance.dispose();
  }

  shipmentChartInstance = echarts.init(shipmentChart.value);

  console.log('📊 开始绘制发货图表，AI预测:', shipmentPrediction.value);

  // 真实历史数据（每条发货记录的实际数量，已经是倒序：从最晚到最早）
  const historicalData = shipments.map(s => ({
    value: s.count || 0,
    shipmentNo: s.shipmentNo || '',
    date: s.date || ''
  }));
  
  // X轴时间标签（从最晚到最早，格式化显示）
  const timeLabels = shipments.map(s => {
    const date = new Date(s.date);
    return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${String(date.getMinutes()).padStart(2, '0')}`;
  });

  // AI预测数据（未来7天）
  const predictionValues = shipmentPrediction.value.prediction || [];
  const lastDate = shipments.length > 0 ? new Date(shipments[0].date) : new Date();
  const predictionLabels = [];
  for (let i = 1; i <= 7; i++) {
    const futureDate = new Date(lastDate);
    futureDate.setHours(futureDate.getHours() + i);
    predictionLabels.push(`${futureDate.getMonth() + 1}-${futureDate.getDate()} ${futureDate.getHours()}:${String(futureDate.getMinutes()).padStart(2, '0')}`);
  }

  // 合并X轴标签（历史 + 预测）
  const allLabels = [...timeLabels, ...predictionLabels];

  // 历史数据系列（包含最后一个点连接到预测）
  const historicalSeries = [...historicalData.map(d => d.value), historicalData.length > 0 ? historicalData[0].value : 0];

  // 预测数据系列（从最后一个历史数据点开始，前面用'-'占位使得连续）
  const lastHistoricalValue = historicalData.length > 0 ? historicalData[0].value : 0;
  const predictionSeries = [...historicalData.map(() => '-'), lastHistoricalValue, ...predictionValues];

  // 计算Y轴最大值（包含预测数据）
  const allValues = [...historicalData.map(d => d.value), ...predictionValues].filter(v => v > 0);
  const maxValue = yMax || (allValues.length > 0 ? Math.max(...allValues) * 1.2 : 100);

  const option = {
    title: {
      text: '发货趋势分析（真实数据 + AI预测）',
      textStyle: { fontSize: 14, fontWeight: 'normal' }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'cross' },
      formatter: function(params) {
        let result = `时间: ${params[0].axisValue}<br/>`;
        params.forEach(param => {
          if (param.value !== null && param.value !== undefined) {
            result += `${param.seriesName}: ${Math.round(param.value)} 单<br/>`;
          }
        });
        return result;
      }
    },
    legend: {
      data: ['历史数据', 'AI预测'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: allLabels,
      name: '时间（左：历史数据，右：AI预测）',
      nameLocation: 'middle',
      nameGap: 30,
      axisLabel: {
        rotate: 45,
        interval: 'auto',
        formatter: function(value) {
          return value;
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '发货数量（单）',
      nameLocation: 'middle',
      nameGap: 50,
      min: 0,
      max: maxValue,
      axisLine: {
        show: true,
        lineStyle: {
          color: '#ddd'
        }
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#f0f0f0',
          type: 'dashed'
        }
      },
      axisLabel: {
        formatter: '{value}'
      }
    },
    series: [
      {
        name: '历史数据',
        type: 'line',
        data: historicalSeries,
        smooth: false,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: '#91cc75'
        },
        lineStyle: {
          width: 3
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(145, 204, 117, 0.3)' },
            { offset: 1, color: 'rgba(145, 204, 117, 0.05)' }
          ])
        }
      },
      {
        name: 'AI预测',
        type: 'line',
        data: predictionSeries,
        smooth: true,
        symbol: 'diamond',
        symbolSize: 10,
        itemStyle: {
          color: '#fac858'
        },
        lineStyle: {
          width: 3,
          type: 'dashed'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(250, 200, 88, 0.2)' },
            { offset: 1, color: 'rgba(250, 200, 88, 0.05)' }
          ])
        }
      }
    ]
  };

  shipmentChartInstance.setOption(option);
};

/**
 * 绘制库存趋势图（真实数据 + AI预测，从最晚到最早）
 */
const renderInventoryChart = (inventory, yMax) => {
  if (!inventoryChart.value) return;

  if (inventoryChartInstance) {
    inventoryChartInstance.dispose();
  }

  inventoryChartInstance = echarts.init(inventoryChart.value);

  console.log('📊 开始绘制库存图表，AI预测:', inventoryPrediction.value);

  // 真实历史数据（每条库存记录的实际数量，已经是倒序：从最晚到最早）
  const historicalData = inventory.map(i => ({
    value: i.inventory || 0,
    productName: i.productName || '',
    date: i.date || ''
  }));
  
  // X轴时间标签（从最晚到最早，格式化显示）
  const timeLabels = inventory.map(i => {
    const date = new Date(i.date);
    return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${String(date.getMinutes()).padStart(2, '0')}`;
  });

  // AI预测数据（未来7天）
  const predictionValues = inventoryPrediction.value.prediction || [];
  const lastDate = inventory.length > 0 ? new Date(inventory[0].date) : new Date();
  const predictionLabels = [];
  for (let i = 1; i <= 7; i++) {
    const futureDate = new Date(lastDate);
    futureDate.setHours(futureDate.getHours() + i);
    predictionLabels.push(`${futureDate.getMonth() + 1}-${futureDate.getDate()} ${futureDate.getHours()}:${String(futureDate.getMinutes()).padStart(2, '0')}`);
  }

  // 合并X轴标签（历史 + 预测）
  const allLabels = [...timeLabels, ...predictionLabels];

  // 历史数据系列（包含最后一个点连接到预测）
  const historicalSeries = [...historicalData.map(d => d.value), historicalData.length > 0 ? historicalData[0].value : 0];

  // 预测数据系列（从最后一个历史数据点开始，前面用'-'占位使得连续）
  const lastHistoricalValue = historicalData.length > 0 ? historicalData[0].value : 0;
  const predictionSeries = [...historicalData.map(() => '-'), lastHistoricalValue, ...predictionValues];

  // 计算Y轴最大值（包含预测数据）
  const allValues = [...historicalData.map(d => d.value), ...predictionValues].filter(v => v > 0);
  const maxValue = yMax || (allValues.length > 0 ? Math.max(...allValues) * 1.2 : 100);

  const option = {
    title: {
      text: '库存趋势分析（真实数据 + AI预测）',
      textStyle: { fontSize: 14, fontWeight: 'normal' }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'cross' },
      formatter: function(params) {
        let result = `时间: ${params[0].axisValue}<br/>`;
        params.forEach(param => {
          if (param.value !== null && param.value !== undefined) {
            result += `${param.seriesName}: ${Math.round(param.value)} 件<br/>`;
          }
        });
        return result;
      }
    },
    legend: {
      data: ['历史数据', 'AI预测'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: allLabels,
      name: '时间（左：历史数据，右：AI预测）',
      nameLocation: 'middle',
      nameGap: 30,
      axisLabel: {
        rotate: 45,
        interval: 'auto',
        formatter: function(value) {
          return value;
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '库存数量（件）',
      nameLocation: 'middle',
      nameGap: 50,
      min: 0,
      max: maxValue,
      axisLine: {
        show: true,
        lineStyle: {
          color: '#ddd'
        }
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#f0f0f0',
          type: 'dashed'
        }
      },
      axisLabel: {
        formatter: '{value}'
      }
    },
    series: [
      {
        name: '历史数据',
        type: 'line',
        data: historicalSeries,
        smooth: false,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: '#73c0de'
        },
        lineStyle: {
          width: 3
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(115, 192, 222, 0.3)' },
            { offset: 1, color: 'rgba(115, 192, 222, 0.05)' }
          ])
        }
      },
      {
        name: 'AI预测',
        type: 'line',
        data: predictionSeries,
        smooth: true,
        symbol: 'diamond',
        symbolSize: 10,
        itemStyle: {
          color: '#fc8452'
        },
        lineStyle: {
          width: 3,
          type: 'dashed'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(252, 132, 82, 0.2)' },
            { offset: 1, color: 'rgba(252, 132, 82, 0.05)' }
          ])
        }
      }
    ]
  };

  inventoryChartInstance.setOption(option);
};

/**
 * 窗口大小改变时重新渲染图表
 */
const handleResize = () => {
  orderChartInstance?.resize();
  shipmentChartInstance?.resize();
  inventoryChartInstance?.resize();
};

/**
 * 初始化SignalR连接
 */
const initSignalR = async () => {
  try {
    // 创建SignalR连接
    connection = new signalR.HubConnectionBuilder()
      .withUrl('/api/signalr/AIReportHub', {
        skipNegotiation: true,
        transport: signalR.HttpTransportType.WebSockets
      })
      .withAutomaticReconnect() // 自动重连
      .build();

    // 监听数据更新事件
    connection.on('ReceiveDataUpdate', (data) => {
      console.log('📡 收到实时数据更新:', data);
      
      // 更新预测数据
      if (data.prediction) {
        orderPrediction.value = data.prediction.order || orderPrediction.value;
        shipmentPrediction.value = data.prediction.shipment || shipmentPrediction.value;
        inventoryPrediction.value = data.prediction.inventory || inventoryPrediction.value;
        suggestions.value = data.prediction.suggestions || [];
        updateTime.value = new Date().toLocaleString();
      }

      // 重新渲染图表（使用真实数据和Y轴范围）
      nextTick(() => {
        const yAxisRanges = data.yAxisRanges || {};
        renderOrderChart(data.orders, yAxisRanges.orderMax);
        renderShipmentChart(data.shipments, yAxisRanges.shipmentMax);
        renderInventoryChart(data.inventory, yAxisRanges.inventoryMax);
      });
    });

    // 连接断开事件
    connection.onclose(() => {
      console.log('❌ SignalR连接已断开');
    });

    // 重连事件
    connection.onreconnecting(() => {
      console.log('🔄 SignalR正在重连...');
    });

    connection.onreconnected(() => {
      console.log('✅ SignalR已重新连接');
    });

    // 启动连接
    await connection.start();
    console.log('✅ SignalR连接成功');
    
    // 加入AI报表分析组
    await connection.invoke('JoinGroup', 'AIReport');
    console.log('✅ 已加入AI报表分析实时更新组');
    
    // 启动服务器端定时推送（每秒更新一次）
    await proxy.http.post('/api/AIReport/StartAutoPush');
    console.log('✅ 已启动服务器端定时推送（1秒/次）');
    
  } catch (error) {
    console.error('❌ SignalR连接失败:', error);
  }
};

/**
 * 组件挂载
 */
onMounted(async () => {
  // 初始加载数据
  await loadData();
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize);
  
  // 初始化SignalR实时连接
  await initSignalR();
});

/**
 * 组件卸载
 */
onUnmounted(async () => {
  // 清理图表实例
  orderChartInstance?.dispose();
  shipmentChartInstance?.dispose();
  inventoryChartInstance?.dispose();
  
  // 移除窗口监听
  window.removeEventListener('resize', handleResize);
  
  // 停止服务器端定时推送
  try {
    await proxy.http.post('/api/AIReport/StopAutoPush');
    console.log('✅ 已停止服务器端定时推送');
  } catch (error) {
    console.error('❌ 停止定时推送失败:', error);
  }
  
  // 断开SignalR连接
  if (connection) {
    try {
      await connection.invoke('LeaveGroup', 'AIReport');
      await connection.stop();
      console.log('✅ SignalR连接已断开');
    } catch (error) {
      console.error('❌ 断开SignalR连接失败:', error);
    }
  }
});
</script>

<style scoped lang="less">
.ai-report-container {
  position: relative;
  width: 100%;
  min-height: 100vh;
  background: #f5f7fa;
}

.report-content {
  padding: 20px;
  padding-bottom: 40px;
}

.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

  .header-title {
    h2 {
      margin: 0;
      font-size: 24px;
      color: #303133;
    }

    .subtitle {
      margin: 5px 0 0 0;
      font-size: 14px;
      color: #909399;
    }
  }

  .header-actions {
    display: flex;
    gap: 12px;
  }
}

.update-time {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
  padding: 12px 20px;
  background: #ecf5ff;
  border-radius: 6px;
  color: #409eff;
  font-size: 14px;
}

.suggestions-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);

  .card-title {
    display: flex;
    align-items: center;
    gap: 8px;
    color: white;
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 15px;
  }

  .suggestions-list {
    display: flex;
    flex-direction: column;
    gap: 10px;

    .suggestion-item {
      background: rgba(255, 255, 255, 0.95);
      padding: 12px 16px;
      border-radius: 8px;
      color: #303133;
      font-size: 14px;
      line-height: 1.6;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
  }
}

.charts-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
  
  @media (max-width: 1400px) {
    grid-template-columns: 1fr;
  }
}

.chart-card {
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;

    .card-title {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 16px;
      font-weight: bold;
      color: #303133;
    }
  }

  .chart-wrapper {
    width: 100%;
    height: 320px;
    margin-bottom: 10px;

    .chart {
      width: 100%;
      height: 100%;
    }
  }

  .prediction-text {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    margin-top: 15px;
    padding: 15px;
    background: #f4f4f5;
    border-radius: 8px;
    font-size: 14px;
    line-height: 1.6;
    color: #606266;

    .el-icon {
      margin-top: 2px;
      flex-shrink: 0;
      color: #409eff;
    }
  }
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-bottom: 20px;
  
  @media (max-width: 1200px) {
    grid-template-columns: repeat(2, 1fr);
  }
  
  @media (max-width: 768px) {
    grid-template-columns: 1fr;
  }
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 20px;
  background: white;
  padding: 25px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s, box-shadow 0.3s;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  }

  .stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28px;
    color: white;

    &.order-icon {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }

    &.shipment-icon {
      background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    }

    &.inventory-icon {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    }
  }

  .stat-content {
    flex: 1;

    .stat-label {
      font-size: 14px;
      color: #909399;
      margin-bottom: 8px;
    }

    .stat-value {
      font-size: 28px;
      font-weight: bold;
      color: #303133;

      .unit {
        font-size: 14px;
        color: #909399;
        font-weight: normal;
        margin-left: 5px;
      }
    }
  }
}
</style>

